class Solution(object):
    def bagOfTokensScore(self, tokens, power):
        max_count = 0
        tokens.sort()
        n = len(tokens)
        left = 0
        right = n - 1
        now = 0
        while left <= right:
            if power >= tokens[left]:
                power -= tokens[left]
                left += 1
                now += 1
                max_count = max(now, max_count)
            else:
                if now >= 1:
                    power += tokens[right]
                    right -= 1
                    now -= 1
                else:
                    break
        return max_count


data = Solution()
tokens = [100, 200, 300, 400]
power = 200
print(data.bagOfTokensScore(tokens, power))
